package com.ktgj.pay.controller;

import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.pay.payUtil.UnionPayUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

@ControllerAdvice
@RestController
@RequestMapping("unionPay")
public class UnionPayController {

    @GetMapping("getUnionPayParam")
    public AjaxResult getUnionPayParam(String type, String notifyUrl, String orderIdParam, BigDecimal priceParam) {
        return AjaxResult.success(UnionPayUtil.getUnionPayParam(type, notifyUrl, orderIdParam, priceParam));
    }

    /**
     * 银联支付（远程）
     * */
    @PostMapping("/postUnionPayParam")
    public String postUnionPayParam(@RequestBody Map<String, Object> map) {
        String type = null;
        String notifyUrl = map.get("notifyUrl").toString();
        String orderIdParam = map.get("orderIdParam").toString();
        BigDecimal priceParam = new BigDecimal(map.get("priceParam").toString());
        String unionPayParam = UnionPayUtil.getUnionPayParam(type, notifyUrl, orderIdParam, priceParam);
        if (unionPayParam != null && !unionPayParam.equals("")){
            return unionPayParam;
        }
        else {
            return null;
        }

    }


    //支付成功后回调测试(云闪付（银联）回调必须是post方式的回调)
    @PostMapping("test")//notifyUrl = "pay/unionPay/test"
    public void test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UnionPayUtil.isPaySuccessful(req);
        //返回给银联服务器http 200  状态码
        resp.getWriter().print("ok");//****云闪付（银联）支付回调接口，必须要有这行代码****
    }


    //验证支付是否成功
    @GetMapping("isPaySuccessful")
    public String isPaySuccessful(HttpServletRequest request) {
        boolean bool = false;
        try {
            bool = UnionPayUtil.isPaySuccessful(request);
            if (bool)
                return "true";
            else
                return "false";
        } catch (Exception e) {
            return "error";//支付回调失败
        }
    }

}
